import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
path = 'E:\Program Files\Python37\代码\python\机器学习\ex1data1.txt'
data = pd.read_csv(path,header=None,names=['Population','Profit'])

data.plot(kind='scatter',x='Population',y='Profit',figsize=(8,5))
plt.show()

def compute_cost(X,y,theta):
    inner=np.power(((X@theta.T)-y),2)
    return sum(inner)/(2*len(X))

data.insert(0,'ones',1)
cols=data.shape[1]
X=data.iloc[:,:-1]
y=data.iloc[:,cols-1:cols]
theta=np.array([0,0]).reshape(1,2)
X=np.array(X)
y=np.array(y)
print('X.shape=',X.shape,'y.shape=',y.shape,'theta.shape=',theta.shape)


def gradientDescent(X,y,theta,alpha,epoch):
    temp=np.array(np.zeros(theta.shape))
    parameters=int(theta.flatten().shape[0])
    cost=np.zeros(epoch)
    m=X.shape[0]
    for i in range(epoch):
        temp=theta-(alpha/m)*(X@theta.T-y).T@(X)
        theta=temp
        cost[i]=compute_cost(X,y,theta)
    return theta,cost


alpha = 0.01
epoch = 2000
final_theta, cost = gradientDescent(X, y, theta, alpha, epoch)
final_cost=compute_cost(X,y,final_theta)
print(final_cost)

population = np.linspace(data.Population.min(), data.Population.max(), 100) # 横坐标
profit = final_theta[0,0] + (final_theta[0,1] * population) # 纵坐标，利润

fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(population, profit, 'r', label='Prediction')
ax.scatter(data['Population'], data['Profit'], label='Training data')
ax.legend(loc=4) # 4表示标签在右下角
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title('Prediction Profit by. Population Size')
plt.show()
